<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="选择店铺：" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择店铺" filterable>
          <el-option v-for="(item,index) in storeList" :key="index"
                     :label="item.storeUserName + ' - ' + item.storeName "
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="店铺名称" prop="storeId">-->
      <!--        <el-select size="small" v-model="queryParams.storeId" placeholder="请选择店铺名称" clearable filterable>-->
      <!--          <el-option v-for="(dict,index) in storeList" :key="index" :label="dict.storeUserName+' &#45;&#45; '+dict.storeName"-->
      <!--                     :value="dict.id"/>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="订单号" prop="orderId">
        <el-input size="small" v-model="queryParams.orderId" placeholder="请输入订单号"/>
      </el-form-item>
      <el-form-item label="提成类型" prop="commissionFlag">
        <el-select size="small" v-model="queryParams.commissionFlag" placeholder="请选择提成类型" clearable filterable>
          <el-option v-for="(dict,index) in dict.type.commission_type" :key="index"
                     :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">-->
      <!--          删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeUserRelateList" @selection-change="handleSelectionChange" border stripe
              :header-cell-class-name="addClass">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="店铺账号" prop="storeUserName" align="center"></el-table-column>
      <el-table-column label="订单号" prop="orderId" align="center"></el-table-column>
      <el-table-column label="订单状态" prop="erpInnerOrderStatus" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_inner_order_status" :value="scope.row.erpInnerOrderStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="预计可得" prop="expectObtain" align="center"></el-table-column>
      <el-table-column label="退款金额" prop="refundAmount" align="center"></el-table-column>
      <!--      <el-table-column label="订单金额" prop="payPrice" align="center"></el-table-column>-->
      <!--      <el-table-column label="联盟佣金" prop="afflicateFeeRate" align="center"></el-table-column>-->
      <!--      <el-table-column label="交易佣金" prop="escrowFeeRate" align="center"></el-table-column>-->
      <el-table-column label="商品费用" prop="productFee" align="center">
        <template slot-scope="scope">
          <div @click="openPurchaseVoucherModal(scope.row)" class="fontSize12 changeHand"
               :class="scope.row.productFee?'text-danger':'text-blue' ">
            {{ scope.row.productFee ? scope.row.productFee : '上传采购凭证' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物流费用" prop="logisticsFee" align="center">
        <template slot-scope="scope">
          <div @click="openLogisticsVoucherModal(scope.row)" class="fontSize12 changeHand"
               :class="scope.row.logisticsFee?'text-danger':'text-blue' ">
            {{ scope.row.logisticsFee ? scope.row.logisticsFee : '上传物流凭证' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="货代费用" prop="freightForwardingFee" align="center"></el-table-column>
      <el-table-column label="其他费用" prop="otherAmount" align="center"></el-table-column>
      <el-table-column label="订单利润" prop="profit" align="center"></el-table-column>
      <el-table-column label="提成比例" prop="commissionRate" align="center"></el-table-column>
      <el-table-column label="提成金额" prop="commissionAmount" align="center"></el-table-column>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!--  上传采购凭证  -->
    <purchaseVoucher v-if="isOpenPurchaseVocherModal" :orderId="orderId" :isCommission="true"
                     :voucherInfo="purchaseVoucherInfo"
                     @closePurchaseVoucherModal="closePurchaseVoucheModal"></purchaseVoucher>
    <!--  上传物流凭证  -->
    <logisticsVoucher v-if="isOpenLogisticsVoucherModal" :orderId="orderId" :voucherInfo="logisticsVoucherInfo"
                      @closeLogisticsVoucherModal="closeLogisticsVoucherModal"></logisticsVoucher>
  </div>
</template>

<script>
import {
  delProductUserRelate, queryOrderCommissionList, getStoreList, restTrial
} from "@/api/commission/commission";
import logisticsVoucher from "@/views/order/supplementOrder/logisticsVoucher.vue";
import purchaseVoucher from "@/views/order/supplementOrder/purchaseVoucher.vue";
import {getLogisticsProof} from "@/api/order/supplementOrder";
import {getPurchaseProofList} from "@/api/commission/orderCommission"
import {getStoreInfo} from "@/api/order/orderApi";

export default {
  name: "StoreUserRelate",
  components: {logisticsVoucher, purchaseVoucher},
  dicts: ['erp_product_type', 'commission_type', 'erp_inner_order_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户店铺维护关联表格数据
      storeUserRelateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        storeId: undefined,
        commissionFlag: undefined,
        orderId: undefined
      },
      // 表单参数
      form: {
        storeGradRelateList: [{
          "type": '1',
          "gradRate": '',
          'aeProductId': ''
        }]
      },
      productList: [],//店铺列表
      dateTime: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      storeList: [],//店铺列表
      queryData: "",
      isOpenPurchaseVocherModal: false,//是否打开上传采购凭证模态框
      isOpenLogisticsVoucherModal: false,//是否打开上传物流凭证模态框
      orderId: "",
      purchaseVoucherInfo: "",
      logisticsVoucherInfo: ""
    };
  },
  created() {
    console.log('this.$router.query', this.$route.query)
    if (this.$route.query.queryData) {
      this.queryData = JSON.parse(this.$route.query.queryData)
      const mergedObj = {...this.queryParams, ...this.queryData}
      this.queryParams = mergedObj
      console.log(' this.queryParams', this.queryParams)
      // this.queryParams.userId = this.queryData.userId
      // this.queryParams.storeId = this.queryData.storeId
      // this.queryParams.commissionFlag = this.queryData.commissionFlag
      // this.queryParams.searchTime = this.queryData.searchTime
    }
    this.getList();
    this.getStoreList()
  },
  methods: {
    // 打开上传采购凭证弹窗
    openPurchaseVoucherModal(row) {
      this.orderId = row.orderId
      this.childOrderId = row.childOrderId
      this.getSendGoodsInfo()
    },
    // 获取已上传的采购凭证
    getSendGoodsInfo() {
      getPurchaseProofList({
        orderId: this.orderId
      }).then(res => {
        this.purchaseVoucherInfo = res.data
        this.isOpenPurchaseVocherModal = true
      })
    },
    // 打开上传物流凭证弹窗
    openLogisticsVoucherModal(row) {
      this.orderId = row.orderId
      this.getLogisticsProof('0')
    },
    // 获取已上传的物流凭证信息
    getLogisticsProof(e) {
      getLogisticsProof({orderId: this.orderId}).then(res => {
        this.logisticsVoucherInfo = res.data
        this.isOpenLogisticsVoucherModal = true
      })
    },
    // 关闭上传物流凭证弹窗
    closeLogisticsVoucherModal(e, type) {
      this.isOpenLogisticsVoucherModal = e
      if (type != 'cancel') {
        this.getList()
      }
    },
    // 关闭上传采购信息弹窗
    closePurchaseVoucheModal(e, type) {
      console.log('type', type, e)
      this.isOpenPurchaseVocherModal = e
      if (type != 'cancel') {
        this.getList()
      }
    },
    // 设置表头颜色
    addClass({row, rowIndex, column, columnIndex}) {
      if (columnIndex == 6 || columnIndex == 7) {
        return "redText"
      }
    },
    //  获取店铺列表
    getStoreList() {
      this.loading = true
      getStoreInfo().then(response => {
        this.storeList = response
      })
    },
    // // 获取店铺账号选择列表
    // getStoreList() {
    //   this.loading = true;
    //   getStoreList().then(res => {
    //     this.storeList = res.data.empowerList;
    //     this.loading = false;
    //   });
    // },
    /** 查询用户店铺维护关联列表 */
    getList() {
      this.loading = true;
      // console.log('&&&&', this.queryParams)
      this.queryParams.startTime = this.dateTime[0]
      this.queryParams.endTime = this.dateTime[1]
      queryOrderCommissionList(this.queryParams).then(response => {
        this.storeUserRelateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.queryParams)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户商品提成配置";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userId || this.ids;
      this.$modal.confirm('是否确认删除该用户数据？').then(() => {
        this.loading = true;
        return delProductUserRelate(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('seller/storeUserRelate/export', {
        ...this.queryParams
      }, `storeUserRelate_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-table__header-wrapper th.redText {
  color: #ff0000;
}
</style>
